import ResMgr from './ResMgr';

const { ccclass, property } = cc._decorator;

export class UICtrl extends cc.Component {
    protected view = {};

    private load_all_object(root: cc.Node, path: string): void {
        for (let i = 0; i < root.childrenCount; i++) {
            this.view[path + root.children[i].name] = root.children[i];
            this.load_all_object(root.children[i], path + root.children[i].name + '/');
        }
    }

    protected onLoad(): void {
        this.view = {};
        this.load_all_object(this.node, '');
    }

    public add_button_listen(view_name: string, caller: any, func: Function) {
        const view_node = this.view[view_name];
        if (!view_node) {
            return;
        }
        const button = view_node.getComponent(cc.Button);
        if (!button) {
            return;
        }
        view_node.on('click', func, caller);
    }
}

export default class UIMgr extends cc.Component {
    private Canvas: cc.Node = null;
    public static Instance: UIMgr = null!;
    private UiMap: Object = {};
    protected onLoad(): void {
        if (!UIMgr.Instance) {
            UIMgr.Instance = this;
        } else {
            this.destroy();
            return;
        }
        this.Canvas = this.node.parent;
        console.log(Date.now(), 'UIMgr');
    }

    public show_ui(ui_name: string, parent?: cc.Node) {
        if (!parent) {
            parent = this.Canvas;
        }
        const prefab = ResMgr.Instance.getAsset('GUI', 'UIPrefabs/' + ui_name);
        let item = null;
        if (prefab) {
            item = cc.instantiate(prefab);
            parent.addChild(item);
            item.addComponent(ui_name + '_Ctrl');
        }
        this.UiMap[ui_name] = item;
        return item;
    }

    public hide_ui(ui_name: string) {
        if (this.UiMap[ui_name]) {
            this.UiMap[ui_name].removeFromParent();
        }
    }

    public remove_ui(ui_name: string) {
        if (this.UiMap[ui_name]) {
            this.UiMap[ui_name].destroy();
            this.UiMap[ui_name] = null;
        }
    }

    public clearAll() {
        for (let key in this.UiMap) {
            this.remove_ui(key);
        }
    }
}
